﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace AwesomeEnginePC.Networking.Sockets
{
    public class SocketClient<T> : BaseSocketConnection<T> where T : BaseBrodcastMessage, new()
    {
        Socket clientSocket;

        public SocketClient(IPAddress ipAddress, int port)
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint endPoint = new IPEndPoint(ipAddress, port);

            AddToQueue(SocketMessage.MessageType.Init, null, true, null);

            clientSocket.BeginConnect(endPoint, new AsyncCallback(OnConnect), clientSocket);
        }

        public void SendMessage(T message)
        {
            SendData(message, clientSocket);
        }

        protected override int? GetClientSocketIndex(Socket socket)
        {
            return null;
        }

        private void OnConnect(IAsyncResult asyn)
        {
            AddToQueue(SocketMessage.MessageType.NewConnection, new T(), asyn.IsCompleted, null);

            WaitForData(clientSocket);
        }
    }
}
